package ynu.edu.order.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import ynu.edu.common.domain.R;
import ynu.edu.order.domain.dto.LogisticsFormDTO;
import ynu.edu.order.domain.vo.OrderLogisticsVO;
import ynu.edu.order.service.IOrderLogisticsService;

import javax.validation.Valid;

@Api(tags = "订单物流管理接口")
@RestController
@RequestMapping("/orders/{orderId}/logistics")
@RequiredArgsConstructor
@Slf4j
public class OrderLogisticsController {
    
    private final IOrderLogisticsService logisticsService;

    @ApiOperation("创建订单物流信息")
    @ApiImplicitParam(name = "orderId", value = "订单id", paramType = "path")
    @PostMapping
    public R<Void> createLogistics(
            @PathVariable("orderId") Long orderId,
            @Valid @RequestBody LogisticsFormDTO logisticsFormDTO) {
        try {
            logisticsService.createLogistics(orderId, logisticsFormDTO);
            return R.ok();
        } catch (Exception e) {
            log.error("创建物流信息失败，订单ID: {}", orderId, e);
            return R.error("创建物流信息失败: " + e.getMessage());
        }
    }

    @ApiOperation("更新订单物流信息")
    @ApiImplicitParam(name = "orderId", value = "订单id", paramType = "path")
    @PutMapping
    public R<Void> updateLogistics(
            @PathVariable("orderId") Long orderId,
            @Valid @RequestBody LogisticsFormDTO logisticsFormDTO) {
        try {
            logisticsService.updateLogistics(orderId, logisticsFormDTO);
            return R.ok();
        } catch (Exception e) {
            log.error("更新物流信息失败，订单ID: {}", orderId, e);
            return R.error("更新物流信息失败: " + e.getMessage());
        }
    }

    @ApiOperation("查询订单物流信息")
    @ApiImplicitParam(name = "orderId", value = "订单id", paramType = "path")
    @GetMapping
    public R<OrderLogisticsVO> queryLogistics(@PathVariable("orderId") Long orderId) {
        try {
            OrderLogisticsVO logistics = logisticsService.queryLogistics(orderId);
            if (logistics == null) {
                return R.error("物流信息不存在");
            }
            return R.ok(logistics);
        } catch (Exception e) {
            log.error("查询物流信息失败，订单ID: {}", orderId, e);
            return R.error("查询物流信息失败");
        }
    }

    @ApiOperation("删除订单物流信息")
    @ApiImplicitParam(name = "orderId", value = "订单id", paramType = "path")
    @DeleteMapping
    public R<Void> deleteLogistics(@PathVariable("orderId") Long orderId) {
        try {
            logisticsService.deleteLogistics(orderId);
            return R.ok();
        } catch (Exception e) {
            log.error("删除物流信息失败，订单ID: {}", orderId, e);
            return R.error("删除物流信息失败: " + e.getMessage());
        }
    }
} 